package com.zkx.laolaiyi.handler;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.zkx.laolaiyi.properties.PrivateKeyProperties;
import com.zkx.laolaiyi.utils.EncryptUtil;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 字段自动加解密工具类
 */
@MappedTypes({String.class})
@Slf4j
public class AESEncryptHandler extends BaseTypeHandler<String> {
    private EncryptUtil proxy;
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        String result = EncryptUtil.autoEncryptStringField(parameter);
        log.info("parameter:{}, result: {}", parameter, result);
        ps.setString(i, result);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        return EncryptUtil.autoDecryptStringField(columnValue);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return EncryptUtil.autoDecryptStringField(columnValue);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return EncryptUtil.autoDecryptStringField(columnValue);
    }
}
